import 'package:flutter/material.dart';
import 'package:dio/dio.dart';

class JokePage extends StatefulWidget {
  const JokePage({Key? key}) : super(key: key);

  @override
  State<JokePage> createState() => _JokePageState();
}

class _JokePageState extends State<JokePage> {
  final Dio _dio = Dio();
  String _jokeContent = '';

  // 获取笑话数据
  Future<void> _fetchJoke() async {
    try {
      final response = await _dio.get('https://api-vue-base.itheima.net/api/joke');
      
      // 显示弹窗
      if (context.mounted) {
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('笑话'),
            content: Text(response.data.toString()),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('关闭'),
              ),
            ],
          ),
        );
      }
      
      // 更新状态
      setState(() {
        _jokeContent = response.data.toString();
      });
    } catch (e) {
      // 错误处理
      if (context.mounted) {
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('错误'),
            content: Text('获取笑话失败: ${e.toString()}'),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('关闭'),
              ),
            ],
          ),
        );
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('笑话页面'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            ElevatedButton(
              onPressed: _fetchJoke,
              child: const Text('获取笑话'),
            ),
            const SizedBox(height: 20),
            if (_jokeContent.isNotEmpty)
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Text(
                  _jokeContent,
                  style: const TextStyle(fontSize: 16),
                ),
              ),
          ],
        ),
      ),
    );
  }
}